const gulp = require("gulp");
var less = require("gulp-less");
const browserSync = require("browser-sync").create();
var autoprefixer = require("gulp-autoprefixer");
const postcss = require("gulp-postcss");
const pxtorem = require("postcss-pxtorem");

// less -> css
gulp.task("less", function () {
  return gulp
    .src(["./src/less/*.less"])
    .pipe(less())
    .pipe(
      autoprefixer({
        overrideBrowserslist: ["last 20 versions"],
      })
    )
    .pipe(gulp.dest("./src/css"));
});

// 将 px 转换为 rem 任务
gulp.task("pxtorem", function () {
  const processors = [
    pxtorem({
      rootValue: 40, // 1rem = 40px，根据设计稿调整
      propList: ["*"], // 转换所有属性值
    }),
  ];
  return gulp
    .src("./src/css/*.css") // 源 CSS 文件目录
    .pipe(postcss(processors))
    .pipe(gulp.dest("./src/css")); // 转换后的 CSS 文件输出目录
});

// 浏览器刷新
gulp.task("watch", function (cb) {
  gulp.watch("./src/less/*.less", gulp.series(["less", "pxtorem"]));
  browserSync.init(
    {
      files: ["./src/**/*.*"],
      port: 3002,
      server: {
        baseDir: ["./src"],
      },
    },
    function () {
      console.log("browser refreshed.");
    }
  );
  cb();
});

gulp.task("default", gulp.series("less", "pxtorem", "watch"));
